package top.jacktgq.hsp.netty.tcp_selfprotocal;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;

/**
 * @Author CandyWall
 * @Date 2020/11/13--17:40
 * @Description
 */
public class NettyClientHandler extends SimpleChannelInboundHandler<top.jacktgq.hsp.netty.tcp_selfprotocal.MessageProtocal> {
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        //使用客户端发送10条数据，"今晚10点，铜锣湾12接头"
        String msg = "";
        byte[] msgBytes = msg.getBytes(CharsetUtil.UTF_8);
        //创建协议包对象
        top.jacktgq.hsp.netty.tcp_selfprotocal.MessageProtocal messageProtocal = new top.jacktgq.hsp.netty.tcp_selfprotocal.MessageProtocal(msgBytes.length, msgBytes);
        for (int i = 0; i < 10; i++) {
            ctx.writeAndFlush(messageProtocal);
        }
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, top.jacktgq.hsp.netty.tcp_selfprotocal.MessageProtocal msg) throws Exception {
        //客户端接收客户端发来的消息
        System.out.println("收到来自服务器端的一条消息：" + msg);
    }

    @Override
    //处理异常情况
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println("异常消息");
        ctx.close();
    }
}
